"""多线程TCP IO 密集型并发模型 FTP客户端"""
# !usr/bin/env python3
# coding="UTF-8"
# @author:WeiJunJie
# @email:0234934819@163.com
# @date:2024/1/22
import sys
from socket import *
import time

# 客户端类
class FTPClient:
    ADDR = ("127.0.0.1", 5555)

    def __init__(self):
        self.client = socket()

    # 获取文件库中文件列表
    def do_list(self):
        self.client.send(b"L")  # 发送请求
        # 等待回复
        data = self.client.recv(128).decode()
        if data == "OK":
            data = self.client.recv(4096)
            print(data.decode())
        else:
            print(data)

    def exit(self):
        self.client.send(b"E")
        self.client.close()
        sys.exit("谢谢使用")

    def download(self, filename):
        # 向服务器发送请求
        self.client.send(("D " + filename).encode())
        data = self.client.recv(129).decode()
        if data == "OK":
            f = open(filename, "wb")
            # 循环接收写入文件
            while True:
                data = self.client.recv(1024)
                if data == "##".encode():
                    break
                f.write(data)
            f.close()
        else:
            print(data)

    def upload(self, filename):
        try:
            f = open(filename, "rb")
        except Exception:
            print("你本地没有这个文件")
            self.client.send("Error".encode())
            return
        # 向服务器发送请求
        self.client.send(("U " + filename).encode())
        # 等待服务器响应
        code = self.client.recv(108).decode()
        if code == "OK":
            # 向服务端发送 确认本地有这个文件可以传输的信号
            self.client.send("OK".encode())
            # 暂停1秒防止连续发送过程中粘包
            time.sleep(1)
            while True:
                data = f.read(1024)
                if not data:
                    time.sleep(0.1)
                    self.client.send("##".encode())
                    break
                self.client.send(data)
            f.close()
        else:
            print(code)

    def main(self):
        try:
            self.client.connect(self.ADDR)
        except Exception as e:
            print(e)
            return
        while True:
            print("\n==========命令选项===========")
            print("**********   ls  ************ ")
            print("********** get file  ************ ")
            print("********** put  file  ************ ")
            print("**********   Q  ************ ")
            cmd = input(">>cmd:")
            if cmd == "ls":
                self.do_list()
            elif cmd == "Q":
                self.exit()
                break
            elif cmd[:3] == "get":
                filename = cmd.strip().split(" ")[-1]
                self.download(filename)
            elif cmd[:3] == "put":
                filename = cmd.strip().split(" ")[-1]
                self.upload(filename)

            else:
                print("请输入正确的指令")


if __name__ == "__main__":
    client = FTPClient()
    client.main()